package cloud.xiguapi.ubas.analysis.market;

import cloud.xiguapi.ubas.analysis.market.model.SimulatedMarketingUserBehaviorSource;
import cloud.xiguapi.ubas.analysis.market.model.SummaryMarketingCountAggregate;
import cloud.xiguapi.ubas.analysis.market.model.SummaryMarketingCountResult;
import cloud.xiguapi.ubas.analysis.market.model.SummaryMarketingResult;
import cloud.xiguapi.ubas.model.MarketingUserBehavior;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;
import org.apache.flink.streaming.api.functions.timestamps.AscendingTimestampExtractor;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

import static cloud.xiguapi.ubas.constant.JobNameConstant.SUMMARY_MARKETING;

/**
 * @author 大大大西西瓜皮🍉
 * date: 2021-5-16 下午 12:35
 * desc:
 */
@Component
public class SummaryMarketingAnalysis {

    @Resource(name = "env")
    private StreamExecutionEnvironment env;

    @Async("summaryMarketingAnalysis")
    public void analysis() throws Exception {
        env.setParallelism(8);
        env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);

        // 读取数据源, 模拟
        DataStream<MarketingUserBehavior> inputDataStream = env.addSource(new SimulatedMarketingUserBehaviorSource())
                .assignTimestampsAndWatermarks(new AscendingTimestampExtractor<MarketingUserBehavior>() {
                    @Override
                    public long extractAscendingTimestamp(MarketingUserBehavior element) {
                        return element.getTimestamp();
                    }
                });

        // 开窗聚合
        SingleOutputStreamOperator<SummaryMarketingResult> summaryDataStream = inputDataStream
                .filter(data -> !"UNINSTALL".equalsIgnoreCase(data.getBehavior()))
                .map(new MapFunction<MarketingUserBehavior, Tuple2<String, Long>>() {
                    @Override
                    public Tuple2<String, Long> map(MarketingUserBehavior value) {
                        return new Tuple2<>("total", 1L);
                    }
                })
                .keyBy(0)
                .timeWindow(Time.hours(1L), Time.minutes(10L))
                // .sum(1)// 直接sum得到的结果会是二元组
                .aggregate(new SummaryMarketingCountAggregate(), new SummaryMarketingCountResult());

        summaryDataStream.print();
        summaryDataStream.addSink(new SummaryMarketingMySqlSink());

        env.execute(SUMMARY_MARKETING.getJobName());
    }

    public static class SummaryMarketingMySqlSink extends RichSinkFunction<SummaryMarketingResult> {

        private transient Connection connection;

        private transient PreparedStatement clearStatement;

        private transient PreparedStatement selectStatement;

        private transient PreparedStatement insertStatement;

        private transient PreparedStatement updateStatement;

        private transient boolean isFirst = true;

        @Override
        public void open(Configuration parameters) throws Exception {
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/ubas?serverTimezone=UTC", "root", "1015");
            clearStatement = connection.prepareStatement("TRUNCATE TABLE summary_marketing");
            selectStatement = connection.prepareStatement("SELECT 1 FROM summary_marketing WHERE window_end = ? LIMIT 1");
            insertStatement = connection.prepareStatement("INSERT INTO summary_marketing(window_end, cnt) VALUES(?, ?)");
            updateStatement = connection.prepareStatement("UPDATE summary_marketing SET cnt = ? WHERE window_end = ?");
        }

        @Override
        public void close() throws Exception {
            updateStatement.close();
            selectStatement.close();
            clearStatement.close();
            insertStatement.close();
            connection.close();
        }

        @Override
        public void invoke(SummaryMarketingResult value, SinkFunction.Context context) throws Exception {
            if (isFirst) {
                clearStatement.execute();
                isFirst = false;
                return;
            }

            selectStatement.setString(1, value.getWindowEnd());
            boolean next = selectStatement.executeQuery().next();

            if (next) {
                updateStatement.setLong(1, value.getCnt());
                updateStatement.setString(2, value.getWindowEnd());
                updateStatement.execute();
            } else {
                insertStatement.setString(1, value.getWindowEnd());
                insertStatement.setLong(2, value.getCnt());
                insertStatement.execute();
            }
        }
    }
}
